package com.clw.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.clw.template.entity.SysAdmin;
import com.clw.template.entity.SysStorage;
import com.clw.template.mapper.SysStorageMapper;
import com.clw.template.service.ISysStorageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clw.template.storage.StorageService;
import com.clw.template.util.CharUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 * 文件存储表 服务实现类
 * </p>
 *
 * @author clw
 * @since 2019-11-13
 */
@Service
public class SysStorageServiceImpl extends ServiceImpl<SysStorageMapper, SysStorage> implements ISysStorageService {

    @Autowired
    private StorageService storageService;

    @Override
    public String store(InputStream inputStream, long contentLength, String contentType, String fileName) throws IOException {
        if (contentLength > 1 * 1024 * 1024){
            fileName = fileName.split("\\.")[0] + ".jpg";
            BufferedImage jpg = Thumbnails.of(inputStream).scale(0.5F).outputFormat("jpg").asBufferedImage();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(jpg, "jpg", os);
            inputStream = new ByteArrayInputStream(os.toByteArray());
            contentLength = inputStream.available();
        }
        String key = generateKey(fileName);
        storageService.getStorage().store(inputStream, contentLength, contentType, key);

        String url = generateUrl(key);
        SysStorage storageInfo = new SysStorage();
        storageInfo.setName(fileName);
        storageInfo.setSize((int) contentLength);
        storageInfo.setType(contentType);
        storageInfo.setKey(key);
        storageInfo.setUrl(url);
        save(storageInfo);

        return url;
    }

    @Override
    public SysStorage findByKey(String key) {
        return this.lambdaQuery().eq(SysStorage::getKey,key).one();
    }

    private String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);

        String key = null;
        SysStorage storageInfo = null;

        do {
            key = CharUtil.getRandomString(20) + suffix;
            QueryWrapper<SysStorage> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SysStorage::getKey,key);
            storageInfo = baseMapper.selectOne(queryWrapper);
        }
        while (storageInfo != null);

        return key;
    }

    private String generateUrl(String keyName) {
        return storageService.getStorage().generateUrl(keyName);
    }
}
